package uk.kammakjuj.smsanywhere;

import android.content.Intent;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
import android.text.method.DigitsKeyListener;
import android.widget.EditText;

public class SMSanywhereActivity extends PreferenceActivity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.layout.main);

		// Initially disable the server name and server port options
		CheckBoxPreference cbManualServer = (CheckBoxPreference) getPreferenceScreen()
				.findPreference("cbManualServer");
		if (!cbManualServer.isChecked()) {
			Preference serverPref = (Preference) findPreference("txServerName");
			serverPref.setEnabled(false);
			Preference portPref = (Preference) findPreference("txServerPort");
			portPref.setEnabled(false);
		}

		// Set port preference to only accept numbers
		EditTextPreference txServerPort = (EditTextPreference) getPreferenceScreen()
				.findPreference("txServerPort");
		EditText portEditText = (EditText) txServerPort.getEditText();
		portEditText
				.setKeyListener(DigitsKeyListener.getInstance(false, false));

		final Preference startServerPref = (Preference) findPreference("cbEnable");
		startServerPref
				.setOnPreferenceClickListener(new OnPreferenceClickListener() {

					final Intent intent = new Intent(getApplicationContext(),
							MessageCheckService.class);

					public boolean onPreferenceClick(Preference preference) {
						CheckBoxPreference enablePref = (CheckBoxPreference) getPreferenceScreen()
								.findPreference("cbEnable");
						if (enablePref.isChecked()) {
							startService(intent);
							// startService(new Intent(this,
							// MessageCheckService.class));
						} else {
							stopService(intent);
						}
						return true;
					}

				});

		// Get the manual server preference
		final Preference manualServerPref = (Preference) findPreference("cbManualServer");
		manualServerPref
				.setOnPreferenceClickListener(new OnPreferenceClickListener() {

					public boolean onPreferenceClick(Preference preference) {
						Preference serverPref = (Preference) findPreference("txServerName");
						CheckBoxPreference cbManualServer = (CheckBoxPreference) getPreferenceScreen()
								.findPreference("cbManualServer");
						Preference manualPortPref = (Preference) findPreference("txServerPort");
						if (cbManualServer.isChecked()) {
							serverPref.setEnabled(true);
							manualPortPref.setEnabled(true);
						} else {
							serverPref.setEnabled(false);
							manualPortPref.setEnabled(false);
						}
						return true;
					}

				});
	}
}